const app = getApp()
const adapters = require("../../utils/adapters");
const util = require("../../utils/util");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    header: {
      title: '激活电池',
      whiteBg: false,
      mode: 'back',
      navBarHeight: app.globalData.navBarHeight,
      tabbarHeight: app.globalData.tabbarHeight,
      screenHeight: app.globalData.screenHeight
    },
    activeFormData: {
      sn: '',
      deviceId: '',
      activeDate: '',
      endTime: '',
      city: '',
      phoneNumber: '',
      address: '',
    },
    datePicker: {
      key: '',
      currentDate: new Date().getTime(),
      minDate: new Date().getTime() - 86400000 * 365.25 * 3,
      maxDate: new Date().getTime() + 86400000 * 365.25 * 5,
      show: false,
    },
    device: {},
  },

  onPageScroll(e) {
    this.setData({
      'header.whiteBg': e.scrollTop < 40 ? false : true
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const waitRes = await adapters.waitActive(options.deviceId)
    this.setData({
      activeFormData: waitRes
    })
  },

  onShow() {

  },

  inputValueChange(e) {
    const key = 'activeFormData.' + e.currentTarget.dataset.key;
    const value = e.detail;
  
    this.setData({
      [key]: value
    });
  },

  scanQRCode(e) {
    let targetVariable = e.currentTarget.dataset.variableName;
    const key = `activeFormData.${targetVariable}`;
    wx.scanCode({
      success: (res) => { 
        console.log('扫描结果:', res.result);
        this.setData({
          [key]: res.result  // 使用计算属性名
        });
      },
      fail: (err) => {
        console.log('扫码失败:', err);
        wx.showToast({
          title: '扫码失败，请重试',
          icon: 'none',
        })
      }
    })
  },

  dataPickerShowChange(e) {
    const key = e.currentTarget.dataset.key === undefined ? null : e.currentTarget.dataset.key;
    const show = this.data.datePicker.show

    this.setData({
      "datePicker.key": key,
      "datePicker.show": !show
    })
  },

  dateSelect(event) {
    const key = 'activeFormData.' + this.data.datePicker.key;
    this.setData({
      [key]: util.unixFormatYYMMDD(event.detail),
      "datePicker.show": false
    });
  },

  async active() {
    const activeRes = await adapters.activeBattery(this.data.activeFormData)
    if(activeRes.success) {
      wx.showToast({
        title: '激活成功',
      })
    }else {
      wx.showToast({
        title: '激活失败！' + activeRes.msg,
        icon: 'none'
      })
    }
  }

})